<template>
    <div class="delivery-personnel-content">
        <!-- 主要内容区域 -->
        <div class="main-content">
            <div class="content-card">
                <div class="card-header">
                    <el-icon class="header-icon">
                        <Van />
                    </el-icon>
                    <h2>快送员工作台</h2>
                </div>

                <!-- 统计卡片 -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <el-icon>
                                <Clock />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ stats.pendingOrders }}</div>
                            <div class="stat-label">待接单</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <el-icon>
                                <Loading />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ stats.inProgressOrders }}</div>
                            <div class="stat-label">配送中</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <el-icon>
                                <Check />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">{{ stats.completedOrders }}</div>
                            <div class="stat-label">已完成</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <el-icon>
                                <Money />
                            </el-icon>
                        </div>
                        <div class="stat-content">
                            <div class="stat-number">¥{{ stats.todayEarnings }}</div>
                            <div class="stat-label">今日收入</div>
                        </div>
                    </div>
                </div>

                <!-- 条件筛选 -->
                <div class="filter-bar">
                    <el-form :inline="true" label-width="80px" class="filter-form">
                        <el-form-item label="订单状态">
                            <el-select v-model="orderStatus" placeholder="选择状态" style="width: 180px" @change="onSearch">
                                <el-option v-for="opt in statusOptions" :key="opt.value" :label="opt.label"
                                    :value="opt.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="起点">
                            <el-select v-model="startLocationId" placeholder="选择起点" clearable filterable
                                style="width: 260px">
                                <el-option v-for="opt in locationOptions" :key="opt.value" :label="opt.label"
                                    :value="opt.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="终点">
                            <el-select v-model="endLocationId" placeholder="选择终点" clearable filterable
                                style="width: 260px">
                                <el-option v-for="opt in locationOptions" :key="'end-' + opt.value" :label="opt.label"
                                    :value="opt.value" />
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item>
                            <el-button type="primary" @click="onSearch">查询</el-button>
                            <el-button @click="onReset">重置</el-button>
                        </el-form-item> -->
                    </el-form>
                </div>

                <!-- 订单列表 -->
                <div class="orders-section">
                    <h3>{{ statusLabel }}</h3>

                    <div class="orders-toolbar">
                        <div class="left">
                            <el-checkbox :indeterminate="isIndeterminate" :model-value="isAllChecked"
                                @change="toggleAll">
                                全选
                            </el-checkbox>
                            <span class="sel-count" v-if="selectedIds.length">已选 {{ selectedIds.length }} 单</span>
                        </div>
                        <div class="right">
                            <el-button v-if="orderStatus === 'pending'" size="small" type="primary"
                                :disabled="selectedIds.length === 0" @click="acceptSelected">
                                批量接单
                            </el-button>
                            <el-button v-else-if="orderStatus === 'in_progress'" size="small" type="success"
                                :disabled="selectedIds.length === 0" @click="deliverSelected">
                                批量送达
                            </el-button>
                            <el-button v-else size="small" disabled>
                                批量操作（已送达）
                            </el-button>
                        </div>
                    </div>
                    <div v-if="filteredOrders.length" class="orders-list">
                        <div v-for="order in filteredOrders" :key="order.id" class="order-card">
                            <!-- 头部：订单号 + 时间 + 操作 -->
                            <div class="order-header">
                                <div class="order-meta">
                                    <el-checkbox :model-value="selectedIds.includes(order.id)"
                                        @change="val => toggleOne(order.id, val)" />
                                    <span class="order-id">订单号: {{ order.id }}</span>
                                    <el-tag size="small" type="info" class="time-tag">创建 {{
                                        formatTimestamp(order.createTime) }}</el-tag>
                                    <el-tag v-if="order.scheduledTime" size="small" type="warning" class="time-tag">预约
                                        {{ formatTimestamp(order.scheduledTime) }}</el-tag>
                                </div>
                                <div class="order-actions">
                                    <el-button v-if="orderStatus === 'pending'" type="primary"
                                        @click="acceptOrder(order.id)">接单</el-button>
                                    <el-button v-else-if="orderStatus === 'in_progress'" type="success"
                                        @click="deliverOrder(order.id)">送达</el-button>
                                    <el-button v-else disabled>已送达</el-button>
                                </div>
                            </div>

                            <!-- 主体：起点 / 终点 / 联系方式 -->
                            <div class="order-body">
                                <div class="address-col">
                                    <div class="address-title">起点</div>
                                    <div class="addr-line">
                                        <el-icon>
                                            <Location />
                                        </el-icon>
                                        <span class="primary-address">{{ order.pickupAddress }}</span>
                                    </div>
                                    <div class="detailed-address" v-if="order.pickupDetails">{{ order.pickupDetails }}
                                    </div>
                                </div>
                                <div class="address-col">
                                    <div class="address-title">终点</div>
                                    <div class="addr-line">
                                        <el-icon>
                                            <Location />
                                        </el-icon>
                                        <span class="primary-address">{{ order.deliveryAddress }}</span>
                                    </div>
                                    <div class="detailed-address" v-if="order.deliveryDetails">{{ order.deliveryDetails
                                        }}</div>
                                </div>
                                <div class="contact-col">
                                    <div class="info-item">
                                        <el-icon>
                                            <User />
                                        </el-icon>
                                        <span>{{ order.recipientName }}</span>
                                    </div>
                                    <div class="info-item">
                                        <el-icon>
                                            <Phone />
                                        </el-icon>
                                        <span>{{ order.contactPhone }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <el-empty v-else description="暂无待接订单" />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Van, Clock, Loading, Check, Money, User, Phone, Location } from '@element-plus/icons-vue'
import { getLocationList, getStartToEndOrders, acceptOrder as acceptOrderApi, acceptOrdersBatch, completeDelivery } from '@/api/delivery'
import { formatTimestamp } from '@/utils/date'

// 统计数据
const stats = reactive({
    pendingOrders: 5,
    inProgressOrders: 2,
    completedOrders: 23,
    todayEarnings: 156.8
})

// 待接订单列表（初始示例数据）
const pendingOrders = ref([
    {
        id: 'DL20240106001',
        recipientName: '张三',
        contactPhone: '138****1234',
        deliveryAddress: '1号宿舍楼',
        detailedAddress: '101室',
        createTime: '10:30',
        status: 'pending'
    },
    {
        id: 'DL20240106002',
        recipientName: '李四',
        contactPhone: '139****5678',
        deliveryAddress: '教学楼A座',
        detailedAddress: '3楼301教室',
        createTime: '10:45',
        status: 'pending'
    },
    {
        id: 'DL20240106003',
        recipientName: '王五',
        contactPhone: '137****9012',
        deliveryAddress: '图书馆',
        detailedAddress: '2楼阅览室',
        createTime: '11:00',
        status: 'pending'
    }
])

// 位置筛选
const startLocationId = ref<string | null>(null)
const endLocationId = ref<string | null>(null)
const locationOptions = ref<{ value: string; label: string }[]>([])

// 状态筛选
const statusOptions = [
    { value: 'pending', label: '待接订单' },
    { value: 'in_progress', label: '待送订单' },
    { value: 'delivered', label: '已送订单' }
]
const orderStatus = ref<'pending' | 'in_progress' | 'delivered'>('pending')
const statusLabel = computed(() => statusOptions.find(s => s.value === orderStatus.value)?.label || '订单')

// 过滤后的订单（优先按ID匹配，其次按文本兜底）
const filteredOrders = computed(() => {
    if (!startLocationId.value && !endLocationId.value) return pendingOrders.value
    return pendingOrders.value.filter((o: any) => {
        const startOk = !startLocationId.value
            || o.pickupAddressId === startLocationId.value
            || o.pickupAddress?.includes?.(startLocationId.value as string)
        const endOk = !endLocationId.value
            || o.deliveryAddressId === endLocationId.value
            || o.deliveryAddress?.includes?.(endLocationId.value as string)
        return startOk && endOk
    })
})

// 选择逻辑
const selectedIds = ref<string[]>([])
const isAllChecked = computed(() => selectedIds.value.length > 0 && selectedIds.value.length === filteredOrders.value.length)
const isIndeterminate = computed(() => selectedIds.value.length > 0 && selectedIds.value.length < filteredOrders.value.length)

const toggleAll = (checked?: boolean) => {
    const target = checked === undefined ? !isAllChecked.value : checked
    selectedIds.value = target ? filteredOrders.value.map(o => o.id) : []
}

const toggleOne = (id: string, checked: boolean) => {
    const set = new Set(selectedIds.value)
    if (checked) set.add(id)
    else set.delete(id)
    selectedIds.value = Array.from(set)
}


// 批量接单（控制台打印选中的 id，并调用已有 accept 逻辑逐个处理）
const acceptSelected = async () => {
    if (!selectedIds.value.length) return
    const ids = [...selectedIds.value]
    try {
        // TODO: 替换为真实快送员信息
        await acceptOrdersBatch(ids, 'delivery_user_001')
        ids.forEach(id => acceptOrderLocal(id))
        ElMessage.success(`批量接单成功: ${ids.length} 单`)
    } catch (e) {
        console.error('批量接单失败:', e)
        ElMessage.error('批量接单失败，请稍后重试')
    } finally {
        selectedIds.value = []
    }
}

// 查询与重置
const onSearch = async () => {
    try {
        const params: any = {}
        if (startLocationId.value) params.start = startLocationId.value
        if (endLocationId.value) params.end = endLocationId.value
        params.status = orderStatus.value
        const res = await getStartToEndOrders(params)
        console.log(res)
        if (Array.isArray(res)) {
            pendingOrders.value = res.map((o: any) => ({
                id: o.id,
                recipientName: o.requesterName,
                contactPhone: o.requesterPhone,
                pickupAddressId: o.pickupAddress,
                pickupAddress: locationOptions.value.find(opt => opt.value === o.pickupAddress)?.label || o.pickupAddress,
                pickupDetails: o.pickupDetails,
                deliveryAddressId: o.deliveryAddress,
                deliveryAddress: locationOptions.value.find(opt => opt.value === o.deliveryAddress)?.label || o.deliveryAddress,
                deliveryDetails: o.deliveryDetails,
                createTime: o.createTime,
                scheduledTime: o.scheduledTime,
                status: o.status || orderStatus.value
            }))
        }
    } catch (e) {
        console.error('查询起点终点订单失败:', e)
        // 查询失败维持现有数据
    }
}

const onReset = async () => {
    startLocationId.value = null
    endLocationId.value = null
    orderStatus.value = 'pending'
    // 默认不输入筛选时，调用 getStartToEndOrders 展示结果
    await onSearch()
}

// 初始化地点选项与默认查询
onMounted(async () => {
    try {
        const resp = await getLocationList()
        if (Array.isArray(resp)) {
            locationOptions.value = resp.map((d: any) => ({ value: d.locationId || d.id, label: d.name }))
        }
    } catch (e) {
        console.error('获取地点列表失败:', e)
    }
    await onSearch()
})

// 本地状态更新（成功后调用）
const acceptOrderLocal = (orderId: string) => {
    const orderIndex = pendingOrders.value.findIndex(order => order.id === orderId)
    if (orderIndex > -1) {
        pendingOrders.value.splice(orderIndex, 1)
        stats.pendingOrders = Math.max(0, stats.pendingOrders - 1)
        stats.inProgressOrders += 1
    }
}

// 单个接单
const acceptOrder = async (orderId: string) => {
    try {
        // TODO: 替换为真实快送员信息
        await acceptOrderApi(orderId, 'delivery_user_001')
        acceptOrderLocal(orderId)
        ElMessage.success(`已接单: ${orderId}`)
    } catch (e) {
        console.error('接单失败:', e)
    }
}

// 单个送达
const deliverOrder = async (orderId: string) => {
    try {
        await completeDelivery(orderId)
        const idx = pendingOrders.value.findIndex(o => o.id === orderId)
        if (idx > -1) pendingOrders.value.splice(idx, 1)
        stats.inProgressOrders = Math.max(0, stats.inProgressOrders - 1)
        stats.completedOrders += 1
        ElMessage.success(`已送达: ${orderId}`)
    } catch (e) {
        console.error('送达失败:', e)
        ElMessage.error('送达失败，请稍后重试')
    }
}

// 批量送达
const deliverSelected = async () => {
    if (!selectedIds.value.length) return
    try {
        const ids = [...selectedIds.value]
        for (const id of ids) {
            await completeDelivery(id)
            const idx = pendingOrders.value.findIndex(o => o.id === id)
            if (idx > -1) pendingOrders.value.splice(idx, 1)
        }
        stats.inProgressOrders = Math.max(0, stats.inProgressOrders - ids.length)
        stats.completedOrders += ids.length
        ElMessage.success(`批量送达成功: ${ids.length} 单`)
    } catch (e) {
        console.error('批量送达失败:', e)
        ElMessage.error('批量送达失败，请稍后重试')
    } finally {
        selectedIds.value = []
    }
}

</script>

<style scoped>
.delivery-personnel-content {
    padding: 20px;
}

.main-content {
    display: flex;
    justify-content: center;
    max-width: 1200px;
    margin: 0 auto;
}

.content-card {
    background: white;
    border-radius: 16px;
    padding: 30px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    width: 100%;
    max-width: 1200px;
}

.card-header {
    display: flex;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 2px solid #f0f0f0;
}

.header-icon {
    font-size: 1.5rem;
    color: #3498db;
    margin-right: 12px;
}

.card-header h2 {
    margin: 0;
    font-size: 1.5rem;
    color: #333;
    font-weight: 600;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.filter-bar {
    margin-bottom: 16px;
}

.filter-form :deep(.el-form-item) {
    margin-right: 12px;
}

.detailed-address {
    font-size: 0.9rem;
    color: #666;
    margin-left: 8px;
}

.stat-card {
    background: linear-gradient(135deg, #f8f9ff 0%, #e8f0ff 100%);
    border-radius: 12px;
    padding: 20px;
    display: flex;
    align-items: center;
    border: 1px solid #e0e7ff;
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    background: #3498db;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
}

.stat-icon .el-icon {
    font-size: 1.5rem;
    color: white;
}

.stat-content {
    flex: 1;
}

.stat-number {
    font-size: 1.5rem;
    font-weight: bold;
    color: #333;
    margin-bottom: 4px;
}

.stat-label {
    font-size: 0.9rem;
    color: #666;
}

.orders-section h3 {
    margin: 0 0 20px 0;
    font-size: 1.3rem;
    color: #333;
    font-weight: 600;
}

.orders-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.orders-toolbar .left,
.orders-toolbar .right {
    display: flex;
    align-items: center;
    gap: 8px;
}

.sel-count {
    color: #666;
    font-size: 12px;
}

.orders-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.order-card {
    border: 1px solid #e0e0e0;
    border-radius: 12px;
    padding: 20px;
    background: #fafafa;
    transition: all 0.3s ease;
}

.order-card:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 1px solid #e0e0e0;
}

.order-id {
    font-weight: 600;
    color: #333;
}

.order-meta {
    display: flex;
    align-items: center;
    gap: 8px;
}

.time-tag {
    margin-left: 6px;
}

.order-body {
    display: grid;
    grid-template-columns: 1.2fr 1.2fr 1fr;
    gap: 16px;
}

.address-col,
.contact-col {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.address-title {
    font-weight: 600;
    color: #333;
    margin-bottom: 2px;
}

.addr-line {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #555;
}

.info-item {
    display: flex;
    align-items: center;
    color: #555;
}

.info-item .el-icon {
    margin-right: 8px;
    color: #3498db;
    font-size: 1rem;
}

.order-actions {
    margin-left: 20px;
}


/* 已移除未使用的地址容器相关样式，保留必要的地址列样式 */

@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }

    .order-body {
        grid-template-columns: 1fr;
    }

    .order-actions {
        margin-left: 0;
        width: 100%;
    }

    .order-actions .el-button {
        width: 100%;
    }
}
</style>
